package org.meetunexpectedly.controller.middleground;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.meetunexpectedly.authority.Authority;
import org.meetunexpectedly.entity.user.User;
import org.meetunexpectedly.entity.vo.BasePage;
import org.meetunexpectedly.entity.vo.Result;
import org.meetunexpectedly.entity.vo.UserVO;
import org.meetunexpectedly.service.user.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * @Description: 用户管理控制器
 * @Author: pupil
 * @Date: 2024/09/05 上午 11:25
 */
@RestController
@RequestMapping("/admin/user")
public class AdminUserController {

    @Autowired
    private UserService userService;

    /**
     * 获取用户列表
     *
     * @return
     */
    @GetMapping("/list")
    @Authority("admin:user:list")
    public Result getUserList() {
        return Result.ok().data(userService.list(new LambdaQueryWrapper<User>()));
    }


    /**
     * 分页模糊查询用户
     *
     * @param basePage 基础分页信息
     * @param name     昵称
     * @return
     */
    @GetMapping("/page")
    @Authority("admin:user:page")
    public Result getUserListByPage(BasePage basePage, @RequestParam(required = false) String name) {
        IPage<User> page = userService.getUserListByPage(basePage, name);
        return Result.ok().data(page.getRecords()).count(page.getTotal());
    }

    /**
     * 修改用户
     * @param userVO
     * @return
     */
    @PutMapping
    @Authority("admin:user:update")
    public Result updateUser(@RequestBody @Validated UserVO userVO){
        int count = userService.count(new LambdaQueryWrapper<User>().eq(User::getNickName,userVO.getNickName()).ne(User::getId, userVO.getId()));
        if (count == 1) {
            return Result.error().message("昵称已存在");
        }
        User user = new User();
        user.setId(userVO.getId());
        user.setNickName(userVO.getNickName());
        user.setSex(userVO.getSex());
        if (!userService.updateById(user)) {
            return Result.error().message("修改失败");
        }

        return Result.ok().message("修改成功");
    }

    /**
     * 删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Authority("admin:user:delete")
    public Result deleteUser(@PathVariable Long id){
        if (!userService.deleteUser(id)){
            return Result.error().message("删除失败");
        }
        return Result.ok().message("删除成功");
    }

}
